import { logUnderline, logTitle, logSubTitle, log } from "../utils/index";
function use() {
    logTitle("五、泛型");
    logSubTitle("1、泛型");
    logSubTitle("2、泛型类");
    logSubTitle("3、泛型约束");

    // 泛型类型
    function print<T>(param: T): T {
        return param;
    }

    // 泛型类
    class Demo<T> {
        param!: T;
        add!: (x: T, y: T) => T;
    }
    let demo = new Demo<number>();
    demo.param = 1;
    demo.add = function (x, y) {
        return x + y;
    };

    // 泛型约束
    // ----利用接口
    interface LenthWise {
        length: number;
    }
    // function logLenth1<T>(arg: T): number {
    //     return arg.length; // 改写法报错，因为不是任意T类型都有length
    // }
    function logLenth<T extends LenthWise>(arg: T): number {
        return arg.length;
    }

    // ----在泛型约束中使用类型参数 ??? 待填充
    // function getValue(obj: T, key:K) {
    //     return obj[key];
    // }

    // ----在泛型里使用类类型
    function create<T>(c: { new (): T }): T {
        return new c();
    }

    class BeeKeeper {
        hasMask!: boolean;
    }
    
    class ZooKeeper {
        nametag!: string;
    }
    
    class Animal {
        numLegs!: number;
    }
    
    class Bee extends Animal {
        keeper!: BeeKeeper;
    }
    
    class Lion extends Animal {
        keeper!: ZooKeeper;
    }
    
    function createInstance<A extends Animal>(c: new () => A): A {
        return new c();
    }

    console.log(createInstance(Lion))
    console.log(createInstance(Bee))
    
    // createInstance(Lion).keeper.nametag;  // typechecks!
    // createInstance(Bee).keeper.hasMask;   // typechecks!

    logUnderline();
}

export default { use };
